﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;

using OnlineVideos.Data;
using System.Windows.Media;

using AdRotator;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using OnlineVideos.UI;

namespace VideoMix.Views
{
    public partial class PlayVideoMixPage : PhoneApplicationPage
    {
        #region Global declaration
        List<TimeSpan> Playlistvideos = new List<TimeSpan>();
        List<PlayListTable> listforplaylist = new List<PlayListTable>();
        int PlayListIndex = 0;
        TimeSpan starttime = default(TimeSpan);
        TimeSpan endtime = default(TimeSpan);
        TimelineMarker marker = new TimelineMarker();
        public static bool markerstatus = false;
        #endregion

        #region Constructor
        public PlayVideoMixPage()
        {
            InitializeComponent();
            Loaded += PlayVideoMixPage_Loaded;
        }
        
        #endregion

        #region Methods
        public void youtub()
        {
            try
            {
              

                if (!string.IsNullOrEmpty(AppSettings.YoutubeUri))
                {
                    Uri source = new Uri(AppSettings.YoutubeUri, UriKind.RelativeOrAbsolute);
                    videoMediaElement.Source = source;
                    starttime = TimeSpan.Parse((listforplaylist.Cast<PlayListTable>().ElementAt(PlayListIndex).StartTime));
                    endtime = TimeSpan.Parse((listforplaylist.Cast<PlayListTable>().ElementAt(PlayListIndex).EndTime));
                    videoMediaElement.Play();
                    if (PlayListIndex == listforplaylist.Count)
                    {
                        PlayListIndex = 0;
                    }
                

                }
                PlayListIndex++;
            }
            catch (Exception ex)
            {
             
            }
        }

        public void videoplaylist()
        {
            try
            {
                string url = listforplaylist.Cast<PlayListTable>().ElementAt(PlayListIndex).LinkUrl;
                AppSettings.LinkUrl = string.Empty;
                AppSettings.YoutubeUri = string.Empty;
                AppSettings.LinkUrl = url;
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                wc.DownloadStringAsync(new Uri(url.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "").Replace("http://www.youtube.com/v/", "http://www.youtube.com/watch?v=")));
                wc.DownloadStringCompleted += wc_DownloadStringCompleted;
            }
            catch (Exception ex)
            {
                if (NavigationService.CanGoBack)
                    NavigationService.GoBack();
                
            }
        }
        #endregion

        #region Events
        void PlayVideoMixPage_Loaded(object sender, RoutedEventArgs e)
        {
            int showid=Convert.ToInt32( AppSettings.ShowID);
            Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
            AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
            Adc.IsAdRotatorEnabled = false;

            List<PlayListTable> playlist = Task.Run(async () => await Constants.connection.Table<PlayListTable>().Where(i => i.ShowID == showid).ToListAsync()).Result;
                                         

            listforplaylist.AddRange(playlist.ToList());

            videoplaylist();
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {

                if (AppSettings.LinkUrl != "")
                {
                    AppSettings.YoutubeUri = string.Empty;
                    if (AppSettings.LinkUrl.StartsWith("http://www.dailymotion.com"))
                    {
                        DownloadManagerDailyMotion.dailyDownload(e.Result, dailyQuality.hd720);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://vimeo.com/"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadvideoUrlforVimeoSite(e.Result);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.veoh.com"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetVideoUrlForVeohSite(e.Result);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.metacafe.com"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadVideoUrlFromMetacafeSite(e.Result);

                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.sevenload.com"))
                    {
                        AppSettings.YoutubeUri = "http://ak.cdn.sevenload.net/slcom-production/cdn/" + AppSettings.LinkUrl.Substring(AppSettings.LinkUrl.LastIndexOf("-") + 1) + "/mobile-h264.main-md.mp4";
                    }
                    else if (AppSettings.LinkUrl.Contains("youtube.com"))
                    {
                        AppSettings.YoutubeUri =DownloadManagerHelper.GethtmlData(e.Result);

                    }
                    else
                    {
                        AppSettings.YoutubeUri = AppSettings.LinkUrl;
                    }
                    youtub();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void videoMediaElement_PositionChanged_1(object sender, RoutedPropertyChangedEventArgs<TimeSpan> e)
        {

        }

        private void videoMediaElement_MediaStarting_1(object sender, Microsoft.PlayerFramework.MediaPlayerDeferrableEventArgs e)
        {
            videoMediaElement.StartTime = starttime;
            videoMediaElement.EndTime = endtime;
            //videoMediaElement.LivePosition = starttime;
            videoMediaElement.StartupPosition = starttime;
            marker.Time = endtime;
            videoMediaElement.Markers.Add(marker);
            videoMediaElement.MarkerReached += videoMediaElement_MarkerReached;
            markerstatus = false;
        }

        void videoMediaElement_MarkerReached(object sender, Microsoft.PlayerFramework.TimelineMarkerRoutedEventArgs e)
        {
            if (markerstatus == false)
            {
                videoMediaElement.Stop();
                videoplaylist();
                markerstatus = true;
            }
        }

        private void videoMediaElement_RateChanged_1(object sender, Microsoft.PlayerFramework.RateChangedRoutedEventArgs e)
        {

        }

        private void videoMediaElement_MediaEnded_1(object sender, Microsoft.PlayerFramework.MediaPlayerActionEventArgs e)
        {
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
        }

        private void videoMediaElement_MediaFailed_1(object sender, ExceptionRoutedEventArgs e)
        {
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
        } 
        #endregion
    }
}